<template>
  <div v-show="visible" class="detail-container w-full h-full absolute top-0 left-0 z-3">
    <BasicDetail v-bind="getBindValues" @close="closeHandler">
      <div class="h-full px-4 bg-white overflow-y-scroll">
        <div
          class="h-50px flex items-center font-bold text-base border-b border-slate-100 border-solid"
          >修改公文</div
        >
        <div class="mt-6" v-show="restoreActiviytEnrtyResList.length">
          <RenovateForm :data="renovateFormData" ref="renovateForm" />
        </div>

        <div class="mt-2" v-if="restoreActiviytEnrtyResList.length">
          <ApprovalInformation
            v-model:list="restoreActiviytEnrtyResList"
            :workItemId="workItemId"
          />
        </div>

        <div class="mt-2" v-show="workItemExtendDtoList.length">
          <ExtensionForm :list="workItemExtendDtoList" ref="extensionForm" />
        </div>

        <div class="mt-2" v-show="restorePropResList.length">
          <PropertyForm v-model:list="restorePropResList" ref="propertyForm" />
        </div>
        <div class="mt-2" v-show="restoreRoleResList.length">
          <RoleForm :list="restoreRoleResList" ref="roleForm" />
        </div>
      </div>

      <template #footer>
        <div class="w-full h-full flex items-center">
          <a-button type="primary" @click="submitHandler">保存</a-button>
          <a-button class="ml-4" @click="closeHandler">取消</a-button>
        </div>
      </template>
    </BasicDetail>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, watchEffect, useAttrs, unref, watch, reactive, toRefs } from 'vue';
  import { BasicDetail } from '/@/components/Detail';
  import RenovateForm from './RenovateForm.vue';
  import ApprovalInformation from './ApprovalInformation.vue';
  import ExtensionForm from './ExtensionForm.vue';
  import PropertyForm from './PropertyForm.vue';
  import RoleForm from './RoleForm.vue';
  import { getRestoreWorkItemInfoApi, getRestoreWorkItemApi } from '/@/api/flow/flow';
  import { ComponentTypeEnum } from '/@/components/ModelTable/index';
  import {
    getRequired,
    getDynamicFormData,
    getPropDynamicFormData,
    getRoleDynamicFormData,
  } from './helper';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';
  import { deepMerge } from '/@/utils';

  const props = defineProps({
    visible: Boolean,
    workItemId: Number,
  });

  const emit = defineEmits(['update:visible', 'success']);

  const attrs = useAttrs();

  const loading = ref(false);
  const visibleRef = ref(false);

  const renovateForm = ref<any>(null);
  const extensionForm = ref<any>(null);
  const propertyForm = ref<any>(null);
  const roleForm = ref<any>(null);

  const renovateData = reactive({
    //基础表单
    renovateFormData: {},
    // 流程状态
    restoreActiviytEnrtyResList: [],
    // 属性列表
    restorePropResList: [],
    // 扩展列表
    workItemExtendDtoList: [],
    // 角色列表
    restoreRoleResList: [],
  });

  const {
    renovateFormData,
    restoreActiviytEnrtyResList,
    restorePropResList,
    workItemExtendDtoList,
    restoreRoleResList,
  } = toRefs(renovateData);

  const { createMessage } = useMessage();

  const getBindValues = computed(() => {
    const values = {
      ...attrs,
      visible: unref(visibleRef),
      loading: loading.value,
    };
    return values;
  });

  watchEffect(() => {
    visibleRef.value = !!props.visible;
  });

  //老数据
  let restoreWorkItemDtoOld;

  // 动态表单初始变量
  let workItemExtendDtoListOriginal;
  let restorePropResListOriginal;
  let restoreRoleResListOriginal;

  async function getRestoreWorkItemInfo(workItemId) {
    loading.value = true;
    const res = await getRestoreWorkItemInfoApi({ workItemID: workItemId });

    loading.value = false;

    console.log('res33', res);

    res.restoreActiviytEnrtyResList.forEach((item) => {
      !item.userNames && (item.userNames = null);
    });

    restoreWorkItemDtoOld = res;

    const { workItemName, configTransfer, restoreWorkItemReason } = res;

    renovateData.renovateFormData = {
      workItemName,
      configTransfer,
      restoreWorkItemReason,
    };

    renovateData.restoreActiviytEnrtyResList = cloneDeep(res.restoreActiviytEnrtyResList);

    workItemExtendDtoListOriginal = cloneDeep(res.workItemExtendDtoList);
    restorePropResListOriginal = cloneDeep(res.restorePropResList);
    restoreRoleResListOriginal = cloneDeep(res.restoreRoleResList);

    // 根据数据处理每个类型的表单配置 start
    renovateData.workItemExtendDtoList = res.workItemExtendDtoList.map((item) => {
      const { extendCode, extendName, extendValue, extendType } = item;
      return {
        field: extendCode,
        label: extendName,
        component: ComponentTypeEnum[extendType],
        defaultValue: extendValue,
        componentProps: {
          format: 'YYYY-MM-DD HH:mm:ss',
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
        },
      };
    });
    renovateData.restorePropResList = res.restorePropResList.map((item, index, arr) => {
      const { propID, propName, propValue, dataType, propRequiredFlag, restorePROptionDtoList } =
        item;
      console.log(
        '%cdataType===>157： ',
        'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
        dataType,
      );

      // 获取当前数据的下一个回传的options，做必填判断
      const list = index % 2 == 0 && arr[index + 1]['restorePROptionDtoList'];

      const temp = {
        field: propID,
        label: propName,
        component: ComponentTypeEnum[dataType],
      };
      const schemaTemp =
        !restorePROptionDtoList &&
        deepMerge(temp, {
          defaultValue: propValue,
          required: ({ values }) =>
            getRequired({ values }, propID, { requried: propRequiredFlag, list }),
          componentProps: {
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
          },
        });

      const schemaAssist = deepMerge(temp, {
        defaultValue:
          restorePROptionDtoList &&
          restorePROptionDtoList.length &&
          restorePROptionDtoList[0].value,
        componentProps: {
          options: restorePROptionDtoList,
        },
      });

      const schema = restorePROptionDtoList ? schemaAssist : schemaTemp;

      return schema;
    });

    console.log('renovateData.restorePropResList', renovateData.restorePropResList);

    // 测试切换必填代码
    // const tempRenovate = res.restoreRoleResList.map((item, index) => {
    //   let obj;
    //   if (index) {
    //     console.log('obj23', obj);
    //     obj = deepMerge(item, {
    //       restorePROptionDtoList: [
    //         { label: '否', value: 0 },
    //         { label: '是', value: 1 },
    //       ],
    //     });
    //   } else {
    //     obj = item;
    //   }
    //   return obj;
    // });

    // const renovateList: any = [...tempRenovate];

    // console.log('renovateList', renovateList);

    renovateData.restoreRoleResList = res.restoreRoleResList.map((item, index, arr) => {
      const { roleID, roleName, roleValue, roleType, roleRequiredFlag, restorePROptionDtoList } =
        item;

      // 获取当前数据的下一个回传的options，做必填判断
      const list = index % 2 == 0 && arr[index + 1]['restorePROptionDtoList'];

      const temp = {
        field: roleID,
        label: roleName,
        component: ComponentTypeEnum[roleType],
      };
      const schemaTemp =
        !restorePROptionDtoList &&
        deepMerge(temp, {
          defaultValue:
            roleValue && roleValue.map((item) => ({ userId: item.id, name: item.name })),
          required: ({ values }) =>
            getRequired({ values }, roleID, { requried: roleRequiredFlag, list }),
        });

      const schemaAssist = deepMerge(temp, {
        defaultValue:
          restorePROptionDtoList &&
          restorePROptionDtoList.length &&
          restorePROptionDtoList[0].value,
        componentProps: {
          options: restorePROptionDtoList,
        },
      });

      const schema = restorePROptionDtoList ? schemaAssist : schemaTemp;

      return schema;
    });

    // 根据数据处理每个类型的表单配置 end
  }

  watch(
    () => props.visible,
    (val) => {
      if (val) {
        getRestoreWorkItemInfo(props.workItemId);
      } else {
        renovateData.restoreActiviytEnrtyResList = [];
      }
    },
  );

  function closeHandler() {
    emit('update:visible', false);
  }

  async function submitHandler() {
    let renovateValues;
    let extensionValues;
    let propertyValues;
    let roleValues;

    renovateForm.value && (renovateValues = await renovateForm.value.validate());
    extensionForm.value && (extensionValues = await extensionForm.value.validate());
    propertyForm.value && (propertyValues = await propertyForm.value.validate());
    roleForm.value && (roleValues = await roleForm.value.validate());

    // 通过表单数据处理提交数据 start
    const workItemExtendDtoList = getDynamicFormData(
      workItemExtendDtoListOriginal,
      extensionValues,
      'extendCode',
      'extendValue',
    );

    workItemExtendDtoList.forEach((item) => {
      if (dayjs.isDayjs(item.extendValue)) {
        item.extendValue = item.extendValue.format('YYYY-MM-DD HH:mm:ss');
      }
    });

    console.log('propertyValues2', propertyValues, restorePropResListOriginal);

    const restorePropResList = getPropDynamicFormData(restorePropResListOriginal, propertyValues, [
      'propID',
      'propValue',
      'optionValue',
      'restorePROptionDtoList',
    ]);

    console.log('roleValues2', roleValues, restoreRoleResListOriginal);

    const restoreRoleResList = getRoleDynamicFormData(restoreRoleResListOriginal, roleValues, [
      'roleID',
      'roleValue',
      'optionValue',
      'restorePROptionDtoList',
    ]);

    console.log('extensionValues', extensionValues, workItemExtendDtoListOriginal);
    console.log('propertyValues', propertyValues, restorePropResListOriginal);

    const submitVal = {
      restoreWorkItemDtoOld,
      restoreWorkItemDto: {
        workItemID: props.workItemId,
        ...renovateValues,
        restoreActiviytEnrtyResList: unref(restoreActiviytEnrtyResList),
        workItemExtendDtoList,
        restorePropResList,
        restoreRoleResList,
      },
    };

    // 通过表单数据处理提交数据 end

    console.log('提交', submitVal);

    await getRestoreWorkItemApi(submitVal);

    createMessage.success('修改成功');
    emit('update:visible', false);
    emit('success');
  }
</script>
<style lang="less" scoped></style>
